<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/1/15
 * Time: 15:57
 */
namespace  Mowang\Weather;

use GuzzleHttp\Client;

class Weather
{
    protected $key;
    protected $guzzleOptions = [];

    public function __construct(string $key)
    {
        $this->key = $key;
    }

    public function getHttpClient()
    {
        return new Client($this->guzzleOptions);
    }

    public function setGuzzleOptions(array $options)
    {
        $this->guzzleOptions=$options;
    }

    /**
     * 获取天气
     * @param $city
     * @param string $type
     * @param string $format
     */
    public function getWeather($city, $type='base', $format='json')
    {
        $url = 'https://restapi.amap.com/v3/weather/weatherInfo';
        $query = array_filter([
            'key'=>$this->key,
            'city'=>$city,
            'output'=>$format,
            'extensions'=> $type,
        ]);
        try {
            $response = $this->getHttpClient()->get($url, [
                'query' => $query,
            ])->getBody()->getContents();
            return 'json' === $format ? json_decode($response, true) : $response;
        } catch (\Exception $e) {
            throw new \HttpEncodingException($e->getMessage(), $e->getCode(), $e);
        }
    }

}